package com.honour.busserver.backup.utils;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CronUtil {
    /***
     *
     * @param date
     * @param dateFormat : yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String formatDateByPattern(Date date, String dateFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String formatTimeStr = null;
        if (date != null) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }

    /***
     * convert Date to cron ,eg. "21 25 17 07 01 ? 2020"
     *
     * @param date : 时间点
     * @return
     */
    public static String getCron(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateFormat = "ss mm HH dd MM ? yyyy";
        try {
            return formatDateByPattern(sdf.parse(date), dateFormat);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static Map<String,String> myCron(String time,String date,String type){
        Map<String,String> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        String m = " 0 ";
        String h = " 0 ";
        if(StringUtils.isNotBlank(time)){
            String[] hm = time.split(":");
            h = hm[0];
            m = hm[1];
            sb.append("0 ");
            sb.append(m+ " ");
            sb.append(h+" ");
        }
        String[] mm = date.split(",|，");
        if(type.equals("0")){
            for (int i = 0; i < mm.length; i++) {
               String ds = sb.toString()+mm[i]+" *"+" ? ";
               map.put(mm[i],ds);
            }
        }
        if(type.equals("1")){
            for (int i = 0; i < mm.length; i++) {
                String ds = sb.toString()+"? "+"* "+mm[i];
                map.put(mm[i],ds);
            }
        }
        return map;
    }

}
